/**
*  
* @Function TODO 
* @ProjectName credit-data-platform 
* @PackageName com.py.credit.service.impl    
* @FileName RegionRelationServiceImpl.java    
* @Date 2018年6月1日上午9:34:20
* @Author Min DongXv
* @Copyright (c) 2018, 金电联行 All Rights Reserved.   
*   
*/  
package com.py.credit.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.dao.RegionRelationDao;
import com.py.credit.entity.AreaRelationEntity;
import com.py.credit.service.RegionRelationService;
import com.py.framework.core.entity.SysAreaEntity;
import com.py.framework.core.entity.SysOfficeEntity;

/**
*   
* @Function TODO
* @ClassName RegionRelationServiceImpl   
* @Date 2018年6月1日 上午9:34:20   
* @Author Min DongXv
*       
*/
@Service
public class RegionRelationServiceImpl implements RegionRelationService {

	@Autowired
	private RegionRelationDao regionRelationDao;

	/**
	 * 
	 * @Function 组装区域资源信息
	 * @FileName AchievementCountServiceImpl.java
	 * @MethodName dealRegionResource
	 * @param areas
	 * @return
	 * @Date 2018年5月30日 下午2:04:23
	 * @Author Min DongXv
	 *
	 */
	@Override
	public Map<Long, AreaRelationEntity> dealRegionResource(RestServiceResult<List<SysAreaEntity>> areaResult) {
		// 组装区域MAP对应关系
		Map<Long, AreaRelationEntity> map = getAllAreaMap(areaResult);
		if (null == map) {
			return map;
		}
		// 获取区域资源对应关系
		List<Map<String, Object>> regionResources = regionRelationDao.getRegionResources(null);
		if (!CollectionUtils.isEmpty(regionResources)) {
			for (Map<String, Object> resources : regionResources) {
				if (null != resources && null != resources.get("subscriptionRegion")) {
					Long region = Long.valueOf(String.valueOf(resources.get("subscriptionRegion")));
					if (map.containsKey(region)) {
						AreaRelationEntity areaRelationEntity = map.get(region);
						if (null != resources.get("resourceIds")) {
							String[] strs = StringUtils.split(String.valueOf(resources.get("resourceIds")), ",");
							List<String> resourceIds = new ArrayList<String>(strs.length);
							for (String str : strs) {
								resourceIds.add(str);
							}
							// 区域对应资源关系存入实体
							areaRelationEntity.setResourceIds(resourceIds);
						}
					}
				}
			}
		}
		// 进行各级区域对应资源填充
		for (Entry<Long, AreaRelationEntity> entry : map.entrySet()) {
			AreaRelationEntity areaInfo = entry.getValue();
			if (CollectionUtils.isEmpty(areaInfo.getResourceIds())) {
				String allParent = areaInfo.getAllParentId();
				if (StringUtils.isNotBlank(allParent)) {
					// 有父节点，获取父节点
					String[] strs = StringUtils.split(allParent, ",");
					AreaRelationEntity parentArea = null;
					for (int i = strs.length - 1; i >= 0; i--) {
						parentArea = map.get(Long.valueOf(strs[i]));
						if (null != parentArea && !CollectionUtils.isEmpty(parentArea.getResourceIds())) {
							// 获取父节点的资源填充,有了资源直接返回
							areaInfo.setResourceIds(parentArea.getResourceIds());
							break;
						}
					}
				}
			}
		}
		return map;
	}

	/**
	 * 
	 * @Function 组装部门资源信息 返回部门资源一一对应关系
	 * @FileName AchievementCountServiceImpl.java
	 * @MethodName dealDeptResource
	 * @param areas
	 * @return
	 * @Date 2018年5月30日 下午2:04:23
	 * @Author Min DongXv
	 *
	 */
	@Override
	public Map<Long, Set<String>> dealDeptResource(Map<Long, AreaRelationEntity> regionResources,
			List<SysOfficeEntity> deptResult) {
		Map<Long, Set<String>> result = new HashMap<Long, Set<String>>();
		Map<String, List<String>> deptResources = new HashMap<String, List<String>>();
		if (null != regionResources && !CollectionUtils.isEmpty(deptResult)) {
			for (SysOfficeEntity entity : deptResult) {
				Long areaId = entity.getAreaId();
				String allParent = entity.getAllParentId();
				// 通过区域ID获取区域对应资源信息
				AreaRelationEntity regionResource = regionResources.get(areaId);
				if (null != regionResource && !CollectionUtils.isEmpty(regionResource.getResourceIds())) {
					String parent = "";
					if (StringUtils.isNotBlank(allParent)) {
						// 有父节点，获取父节点
						String[] strs = StringUtils.split(allParent, ",");
						parent = strs[0];
					} else {
						parent = String.valueOf(entity.getId());
					}
					// 直接归属的区域有资源，直接取用
					deptResources.put(parent + "|" + entity.getId(), regionResource.getResourceIds());
				}
			}
		}
		// 获取订阅目录下所有顶级部门对应资源关系
		List<Map<String, Object>> topDeptResources = regionRelationDao.getTopDeptResources();
		if (null != deptResources && !CollectionUtils.isEmpty(topDeptResources)) {
			Map<Long, List<String>> topDeptResourceMap = new HashMap<Long, List<String>>(topDeptResources.size());
			for (Map<String, Object> r : topDeptResources) {
				if (null != r.get("cubeIds")) {
					String[] strs = StringUtils.split(String.valueOf(r.get("cubeIds")), ",");
					List<String> resourceIds = new ArrayList<String>(strs.length);
					for (String str : strs) {
						resourceIds.add(str);
					}
					topDeptResourceMap.put(Long.parseLong(String.valueOf(r.get("deptId"))), resourceIds);
				}
			}
			// 需要匹配部门相关的资源，追溯顶级部门资源，取交集
			for (Entry<String, List<String>> entry : deptResources.entrySet()) {
				List<String> all = entry.getValue();
				String key = entry.getKey();
				String[] keys = StringUtils.split(key, "|");
				Long topDept = Long.parseLong(keys[0]), dept = Long.parseLong(keys[1]);
				List<String> top = topDeptResourceMap.get(topDept);
				Set<String> resources = new HashSet<String>();
				if (!CollectionUtils.isEmpty(all) && !CollectionUtils.isEmpty(top)) {
					// retainAll操作会影响值对象的实际地址里面的值，所以先进行拷贝，用拷贝数据进行操作
					List<String> r = new ArrayList<String>(all.size());
					r.addAll(all);
					// 取交集，不为空录入部门资源信息
					r.retainAll(top);
					if (!CollectionUtils.isEmpty(r)) {
						for (String s : r) {
							resources.add(s);
						}
						result.put(dept, resources);
					}
				}
			}
		}
		return result;
	}

	/**
	 * 
	 * @Function 组装部门资源信息 返回部门对应资源list关系
	 * @FileName RegionRelationServiceImpl.java
	 * @MethodName dealDeptResourceList
	 * @param regionResources
	 * @param deptResult
	 * @return
	 * @Date 2018年6月1日 上午11:20:03
	 * @Author Min DongXv
	 *
	 */
	@Override
	public Map<Long, List<String>> dealDeptResourceList(Map<Long, AreaRelationEntity> regionResources,
			List<SysOfficeEntity> deptResult) {
		Map<Long, List<String>> result = new HashMap<>();
		Map<String, List<String>> deptResources = new HashMap<>();
		if (null != regionResources && !CollectionUtils.isEmpty(deptResult)) {
			for (SysOfficeEntity entity : deptResult) {
				Long areaId = entity.getAreaId();
				String allParent = entity.getAllParentId();
				// 通过区域ID获取区域对应资源信息
				AreaRelationEntity regionResource = regionResources.get(areaId);
				if (null != regionResource && !CollectionUtils.isEmpty(regionResource.getResourceIds())) {
					String parent = "";
					if (StringUtils.isNotBlank(allParent)) {
						// 有父节点，获取父节点
						String[] strs = StringUtils.split(allParent, ",");
						parent = strs[0];
					} else {
						parent = String.valueOf(entity.getId());
					}
					// 直接归属的区域有资源，直接取用
					deptResources.put(parent + "|" + entity.getId(), regionResource.getResourceIds());
				}
			}
		}
		// 获取订阅目录下所有顶级部门对应资源关系
		List<Map<String, Object>> topDeptResources = regionRelationDao.getTopDeptResources();
		if (null != deptResources && !CollectionUtils.isEmpty(topDeptResources)) {
			Map<Long, List<String>> topDeptResourceMap = new HashMap<Long, List<String>>(topDeptResources.size());
			for (Map<String, Object> r : topDeptResources) {
				if (null != r.get("cubeIds")) {
					String[] strs = StringUtils.split(String.valueOf(r.get("cubeIds")), ",");
					List<String> resourceIds = new ArrayList<String>(strs.length);
					for (String str : strs) {
						resourceIds.add(str);
					}
					topDeptResourceMap.put(Long.parseLong(String.valueOf(r.get("deptId"))), resourceIds);
				}
			}
			// 需要匹配部门相关的资源，追溯顶级部门资源，取交集
			for (Entry<String, List<String>> entry : deptResources.entrySet()) {
				List<String> all = entry.getValue();
				String key = entry.getKey();
				String[] keys = StringUtils.split(key, "|");
				Long topDept = Long.parseLong(keys[0]);
				Long dept = Long.parseLong(keys[1]);
				List<String> top = topDeptResourceMap.get(topDept);
				if (!CollectionUtils.isEmpty(all) && !CollectionUtils.isEmpty(top)) {
					// 取交集，不为空录入部门资源信息
					List<String> temp = new ArrayList<String>(all.size());
					temp.addAll(all);
					temp.retainAll(top);
					if (!CollectionUtils.isEmpty(temp)) {
						result.put(dept, temp);
					}
				}
			}
		}
		return result;
	}

	/**
	 * 
	 * @Function 组装区域ID和实体对应MAP
	 * @FileName AchievementCountServiceImpl.java
	 * @MethodName getAllAreaMap
	 * @param areas
	 * @return
	 * @Date 2018年5月30日 下午2:04:23
	 * @Author Min DongXv
	 *
	 */
	@Override
	public Map<Long, AreaRelationEntity> getAllAreaMap(RestServiceResult<List<SysAreaEntity>> areas) {
		// 组装数据
		if (null != areas && RestServiceResult.CODE_SUCCESS == areas.getCode()
				&& !CollectionUtils.isEmpty(areas.getData())) {
			List<SysAreaEntity> areaList = areas.getData();
			Map<Long, AreaRelationEntity> result = new HashMap<Long, AreaRelationEntity>(areaList.size());
			for (SysAreaEntity entity : areaList) {
				if (null != entity) {
					AreaRelationEntity rae = new AreaRelationEntity();
					BeanUtils.copyProperties(entity, rae);
					result.put(entity.getId(), rae);
				}
			}
			return result;
		} else {
			return null;
		}
	}
}
